import { getToken } from './auth'
import socketSdk from 'igw-library/lib/socketSdk'
import store from '@/store'
import { NotificationFunc } from './Notification'
import { debounce } from './debounce'

const notifyMe = debounce(function (data) {
	if (data.msgBody.showType === '1') {
		location.reload()
		return
	} else {
		if (document.hidden) { // 判断是否聚焦当前系统
			NotificationFunc(data, 40000)
			const obj = {
				body: data.msgBody.msgContent,
				icon: require('@/assets/logo/logo.png'),
				silent: true,
				renotify: false,
				when: 1000000
			}
			if (Notification.permission === 'granted') { // 检查用户是否同意接受通知
				const Notif = new Notification(data.msgBody.msgTitle, obj)
				Notif.onclick = function () { // 点击当前消息提示框后，跳转到当前页面
					window.focus()
				}
			} else { // 否则我们需要向用户获取权限
				Notification.requestPermission().then(function (permission) {
					// 如果用户接受权限，我们就可以发起一条消息
					if (permission === 'granted') {
						const Notif = new Notification(data.msgBody.msgTitle, obj)
						Notif.onclick = function () { // 点击当前消息提示框后，跳转到当前页面
							window.focus()
						}
					}
				})
			}
		} else {
			NotificationFunc(data, 4000)
		}
	}
})

var ws = null

setTimeout(() => {
	if (getToken()) {
		// eslint-disable-next-line new-cap
		ws = new socketSdk()
		const url = `ws://${environment()}/socket/connect/ItApp-ProductInfo-Management_1_1_${store.getters.name}_1_token:${getToken().replace(/"/g, '')}`
		// const url = `ws://${location.host}/socket/connect/ItApp-ProductInfo-Management_1_1_${store.getters.name}_1_token:${getToken().replace(/"/g, '')}`
		ws.create({ server: url }, openFuc, msgFuc, errFuc, closeFuc)
	}
}, 1000)

function openFuc(data) { // 建立连接成功
	store.dispatch('globalTips/getCounts')
	Notification.requestPermission()
}

function msgFuc(data) { // 监听后台推送过来的消息
	store.dispatch('globalTips/getCounts')
	notifyMe(data)
}

function errFuc(data) { // 建立连接失败
	store.dispatch('globalTips/getCounts')
}

function closeFuc(data) { }

export function environment() {
	if (process.env.NODE_ENV === 'production') { // 生产
		return `${location.host}`
	} else { // 开发
		return '10.86.130.231:8669'
	}
}
